package com.cskaoyan.utils;

import com.mysql.jdbc.Driver;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * 创建日期: 2022/02/23 11:24
 *
 * @author ciggar
 */
public class JDBCUtils1 {

    // volatile 1. 保证多线程的内存可见性  2. 禁止指令重排序
    static String url = "jdbc:mysql://localhost:3306/37th?useSSL=false&characterEncoding=utf8";
    static String username = "root";
    static String password = "123456";


    // 获取连接
    public static Connection getConnection(){

        Connection connection = null;

        try {
            // 注册驱动
            DriverManager.registerDriver(new Driver());

            // 获取连接
            connection = DriverManager.getConnection(url,username,password);

        }catch (Exception ex){
            ex.printStackTrace();
        }

        return connection;

    }

    // 关闭资源
    public static void releaseResouce(ResultSet resultSet, Statement statement,Connection connection){
        try {
            // 由于Java虚拟机在执行代码的时候可能会指令重排，那么我们需要保证resultSet、statement、connection关闭的先后顺序
            try{
                if(resultSet != null) resultSet.close();
            }finally {
                try{
                    if(statement != null) statement.close();
                }finally {
                    if (connection != null) connection.close();
                }
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }

    }
}
